package com.zjy.controller;

import com.zjy.dao.DepartmentDao;
import com.zjy.dao.EmployeeDao;
import com.zjy.pojo.Department;
import com.zjy.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Collection;


@Controller
public class EmployeeController {
    @Autowired
    DepartmentDao departmentDao;
    @Autowired
    EmployeeDao employeeDao;

    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getEmployees();
        model.addAttribute("emps",employees);

        return "emp/list";
    }
    //get方法一般只完成跳转
    @GetMapping("/emp")
    public String toAdd(Model model) {
        //查出部门的所有信息
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments", departments);
        return "emp/add";
    }
    //post方法可以携带数据
    @PostMapping("/emp")
    public String add(Employee employee) {
        System.out.println(employee);
        //添加的操作
        employeeDao.save(employee);
        return "redirect:/emps";
    }
    @GetMapping("/emp/{id}")
    public String toUpdate(@PathVariable("id") Integer id,Model model){

        //查出原来的数据

        Employee employee = employeeDao.getEmployeeById(id);
        System.out.println(employee);
        model.addAttribute("emp",employee);

        //查出部门信息
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);

        return "emp/update";
    }
    @RequestMapping("/updateEmp")
    public String updataEmp(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }
    @RequestMapping("/delete/{id}")
    public String updataEmp(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
    @RequestMapping("/user/loginout")
    public String loginout(HttpSession session){
        session.invalidate();
        return "redirect:/index.html";
    }

}
